package com.gitee.qdbp.jdbc.plugins.impl;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import com.gitee.qdbp.tools.files.PathTools;
import com.gitee.qdbp.tools.utils.ConvertTools;
import com.gitee.qdbp.tools.utils.StringTools;

/**
 * SQL模板文件扫描接口的Spring实现类
 *
 * @author zhaohuihua
 * @version 20201028
 * @since 3.2.4
 */
public class SpringSqlFileScanner extends BaseSqlFileScanner {

    public SpringSqlFileScanner() {
        super();
    }

    /**
     * 构造函数
     * 
     * @param patterns 扫描规则, 多个以逗号分隔<br>
     *            如: settings/sqls/&#42;&#42;/&#42;.sql, com/xxx/&#42;&#42;/&#42;Dao.xml<br>
     */
    public SpringSqlFileScanner(String patterns) {
        super(patterns);
    }

    /**
     * 构造函数
     * 
     * @param folder 文件夹
     * @param filter 文件名过滤条件
     * @deprecated 作废, 改为{@link SpringSqlFileScanner#SpringSqlFileScanner(String patterns)}<br>
     *             因为按照此配置: folder=a,b; filter=&#42;.sql,&#42;.xml<br>
     *             文件夹a和b下的.sql和.xml都会被扫描; 无法做到a下只扫描.sql, b下只扫描.xml<br>
     */
    @Deprecated
    public SpringSqlFileScanner(String folder, String filter) {
        super(parsePatterns(folder, filter));
    }

    @Override
    protected List<URL> scanSqlFiles(String pattern) throws IOException {
        List<URL> urls = new ArrayList<>();
        String resourcePath = "classpath*:" + pattern;
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources(resourcePath);
        if (resources != null && resources.length > 0) {
            for (Resource resource : resources) {
                urls.add(resource.getURL());
            }
        }
        return urls;
    }

    private static String parsePatterns(String folder, String filter) {
        List<String> patterns = new ArrayList<>();
        String[] folders = StringTools.split(folder, ',');
        String[] filters = StringTools.split(filter, ',');
        for (String fo : folders) {
            for (String fi : filters) {
                patterns.add(PathTools.concat(fo, "**", fi));
            }
        }
        return ConvertTools.joinToString(patterns, ',');
    }
}
